package com.lqq.service.impl;

import com.lqq.api.AccountService;
import com.lqq.api.ProductService;
import com.lqq.dto.OrderDto;
import com.lqq.entity.OrderEntity;
import com.lqq.repository.OrderRepository;
import com.lqq.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.mengyun.tcctransaction.api.Compensable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * @author qingqing.liang
 * @create 2018-01-30
 **/
@Service
//  TODO 在dubbo中使用注解和配置这里的@Service只能使用一个
@Slf4j
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductService productService;

    @Autowired
    private AccountService accountService;


    @Override
    public OrderDto getById(Long id) {
        OrderDto orderDto = new OrderDto();
        OrderEntity orderEntity = orderRepository.findOne(id);
        BeanUtils.copyProperties(orderEntity, orderDto);

        return orderDto;
    }


    private Long getUniqueId(){
        return new Random().nextLong();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    @Compensable(confirmMethod = "confirmOrder", cancelMethod = "cancelOrder")
    public String order(OrderDto orderDto) {

        //生成订单，仓库减少，金额减少
        Long transactionId = getUniqueId();

        //只有一个商品
        productService.record(1L, transactionId);


        //只有一个账户，商品金额是5元
        accountService.record(1L, orderDto.getMoney(), transactionId);

        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(orderDto, orderEntity);

        orderRepository.save(orderEntity);
        return "";
    }

    /**
     * 订单设置为支付成功
     * @param orderDto
     */
    public void confirmOrder(OrderDto orderDto) {

        orderDto.setPayStatus("支付成功");

        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(orderDto, orderEntity);

        orderRepository.save(orderEntity);
    }

    /**
     * 订单设置为未支付
     * @param orderDto
     */
    public void cancelOrder(OrderDto orderDto) {

        orderDto.setPayStatus("未支付");
        OrderEntity orderEntity = new OrderEntity();
        BeanUtils.copyProperties(orderDto, orderEntity);
        orderRepository.save(orderEntity);
    }
}
